<template>
  <div class="user-profile-container">
    <n-card class="profile-card">
      <div class="profile-header">
        <div class="profile-info">
          <div class="avatar-container">
            <n-avatar
              round
              :size="100"
              :src="userInfo.avatar || defaultAvatar"
              fallback-src="/placeholder-avatar.png"
            />
            <n-badge v-if="userInfo.isCreator" dot color="#18a058" :offset="[8, 8]">
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-icon class="creator-badge">
                    <CheckmarkCircle />
                  </n-icon>
                </template>
                认证创作者
              </n-tooltip>
            </n-badge>
          </div>
          <div class="user-info">
            <div class="username">
              {{ userInfo.nickname || userInfo.username }}
              <n-tag v-if="userInfo.level" size="small" type="info" class="level-tag">
                Lv.{{ userInfo.level }}
              </n-tag>
            </div>
            <div class="user-id">ID: {{ userInfo.id }}</div>
            <div class="bio">{{ userInfo.bio || '这个人很懒，什么都没写~' }}</div>
            <div class="stats">
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.workCount }}</div>
                <div class="stat-label">作品</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.followingCount }}</div>
                <div class="stat-label">关注</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.followerCount }}</div>
                <div class="stat-label">粉丝</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.likeCount }}</div>
                <div class="stat-label">获赞</div>
              </div>
            </div>
          </div>
        </div>
        <div class="profile-actions">
          <n-space>
            <n-button v-if="isCurrentUser" @click="editProfile">
              <template #icon><n-icon><PencilOutline /></n-icon></template>
              编辑资料
            </n-button>
            <n-button v-else @click="toggleFollow" :type="userInfo.isFollowed ? 'default' : 'primary'">
              <template #icon><n-icon><PersonAddOutline v-if="!userInfo.isFollowed" /><CheckmarkOutline v-else /></n-icon></template>
              {{ userInfo.isFollowed ? '已关注' : '关注' }}
            </n-button>
            <n-button @click="sendMessage" v-if="!isCurrentUser">
              <template #icon><n-icon><ChatbubbleOutline /></n-icon></template>
              发消息
            </n-button>
            <n-dropdown :options="moreOptions" placement="bottom-end" @select="handleMoreAction">
              <n-button quaternary circle>
                <template #icon><n-icon><EllipsisHorizontal /></n-icon></template>
              </n-button>
            </n-dropdown>
          </n-space>
        </div>
      </div>
    </n-card>

    <div class="content-tabs">
      <n-tabs type="line" animated>
        <n-tab-pane name="works" tab="作品">
          <div class="tab-content">
            <div class="filter-bar">
              <n-space justify="space-between" align="center">
                <n-radio-group v-model:value="worksFilter" size="small">
                  <n-radio-button value="all">全部作品</n-radio-button>
                  <n-radio-button value="original">原创</n-radio-button>
                  <n-radio-button value="popular">热门</n-radio-button>
                </n-radio-group>
                <n-select
                  v-model:value="sortBy"
                  :options="sortOptions"
                  size="small"
                  style="width: 140px"
                />
              </n-space>
            </div>

            <div v-if="userWorks.length > 0" class="works-grid">
              <n-grid :cols="4" :x-gap="16" :y-gap="16" responsive="screen">
                <n-grid-item v-for="work in userWorks" :key="work.id">
                  <n-card hoverable class="work-card" @click="viewWorkDetail(work.id)">
                    <div class="work-thumbnail">
                      <img :src="work.thumbnail" alt="作品缩略图" />
                      <div class="work-duration">{{ formatDuration(work.duration) }}</div>
                    </div>
                    <div class="work-info">
                      <div class="work-title">{{ work.title }}</div>
                      <div class="work-meta">
                        <span class="meta-item">
                          <n-icon><EyeOutline /></n-icon> {{ formatNumber(work.views) }}
                        </span>
                        <span class="meta-item">
                          <n-icon><HeartOutline /></n-icon> {{ formatNumber(work.likes) }}
                        </span>
                        <span class="meta-item">
                          <n-icon><TimeOutline /></n-icon> {{ formatDate(work.createdAt) }}
                        </span>
                      </div>
                    </div>
                  </n-card>
                </n-grid-item>
              </n-grid>
              <div class="pagination">
                <n-pagination
                  v-model:page="currentPage"
                  :page-count="totalPages"
                  :page-size="pageSize"
                  :item-count="totalWorks"
                />
              </div>
            </div>
            <n-empty v-else description="暂无作品" />
          </div>
        </n-tab-pane>

        <n-tab-pane name="collections" tab="收藏">
          <div class="tab-content">
            <div v-if="userCollections.length > 0" class="collections-grid">
              <n-grid :cols="4" :x-gap="16" :y-gap="16" responsive="screen">
                <n-grid-item v-for="collection in userCollections" :key="collection.id">
                  <n-card hoverable class="work-card" @click="viewWorkDetail(collection.id)">
                    <div class="work-thumbnail">
                      <img :src="collection.thumbnail" alt="作品缩略图" />
                      <div class="work-duration">{{ formatDuration(collection.duration) }}</div>
                    </div>
                    <div class="work-info">
                      <div class="work-title">{{ collection.title }}</div>
                      <div class="work-meta">
                        <span class="meta-item">
                          <n-icon><PersonOutline /></n-icon> {{ collection.author }}
                        </span>
                        <span class="meta-item">
                          <n-icon><EyeOutline /></n-icon> {{ formatNumber(collection.views) }}
                        </span>
                        <span class="meta-item">
                          <n-icon><HeartOutline /></n-icon> {{ formatNumber(collection.likes) }}
                        </span>
                      </div>
                    </div>
                  </n-card>
                </n-grid-item>
              </n-grid>
              <div class="pagination">
                <n-pagination
                  v-model:page="collectionsCurrentPage"
                  :page-count="collectionsPages"
                  :page-size="pageSize"
                  :item-count="totalCollections"
                />
              </div>
            </div>
            <n-empty v-else description="暂无收藏" />
          </div>
        </n-tab-pane>

        <n-tab-pane name="about" tab="关于">
          <div class="tab-content">
            <n-card title="个人资料" class="about-card">
              <n-descriptions bordered :column="3">
                <n-descriptions-item label="用户名">
                  {{ userInfo.username }}
                </n-descriptions-item>
                <n-descriptions-item label="注册时间">
                  {{ formatDate(userInfo.createdAt, 'YYYY年MM月DD日') }}
                </n-descriptions-item>
                <n-descriptions-item label="最近活跃">
                  {{ formatDate(userInfo.lastActiveAt, 'YYYY年MM月DD日 HH:mm') }}
                </n-descriptions-item>
                <n-descriptions-item label="个人简介" :span="3">
                  {{ userInfo.bio || '这个人很懒，什么都没写~' }}
                </n-descriptions-item>
              </n-descriptions>
            </n-card>

            <n-card title="社交链接" class="about-card">
              <div v-if="userInfo.socialLinks && userInfo.socialLinks.length > 0">
                <n-space vertical>
                  <div v-for="(link, index) in userInfo.socialLinks" :key="index" class="social-link">
                    <n-button text tag="a" :href="link.url" target="_blank">
                      <template #icon><n-icon><component :is="getSocialIcon(link.platform)" /></n-icon></template>
                      {{ link.displayName || link.platform }}
                    </n-button>
                  </div>
                </n-space>
              </div>
              <n-empty v-else description="暂无社交链接" />
            </n-card>
          </div>
        </n-tab-pane>
      </n-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { DateUtils } from '../../utils/date'
import type { DescriptionsProps } from 'naive-ui'
import {
  NCard,
  NAvatar,
  NBadge,
  NIcon,
  NButton,
  NSpace,
  NTabs,
  NTabPane,
  NTag,
  NRadioGroup,
  NRadioButton,
  NSelect,
  NGrid,
  NGridItem,
  NEmpty,
  NPagination,
  NTooltip,
  NDropdown,
  NDescriptions,
  NDescriptionsItem
} from 'naive-ui'
import {
  PencilOutline,
  PersonAddOutline,
  CheckmarkOutline,
  ChatbubbleOutline,
  EllipsisHorizontal,
  EyeOutline,
  HeartOutline,
  TimeOutline,
  PersonOutline,
  LogoGithub,
  LogoTwitter,
  LogoYoutube,
  LogoInstagram,
  CheckmarkCircle,
  ShareSocialOutline,
  CopyOutline,
  FlagOutline
} from '@vicons/ionicons5'

// 自定义B站图标
const LogoBilibili = () => {
  return h('svg', {
    xmlns: 'http://www.w3.org/2000/svg',
    viewBox: '0 0 24 24',
    width: '1em',
    height: '1em'
  }, [
    h('path', {
      fill: 'currentColor',
      d: 'M17.813 4.653h.854c1.51.054 2.769.578 3.773 1.574 1.004.995 1.524 2.249 1.56 3.76v7.36c-.036 1.51-.556 2.769-1.56 3.773s-2.262 1.524-3.773 1.56H5.333c-1.51-.036-2.769-.556-3.773-1.56S.036 18.858 0 17.347v-7.36c.036-1.511.556-2.765 1.56-3.76 1.004-.996 2.262-1.52 3.773-1.574h.774l-1.174-1.12a1.234 1.234 0 0 1-.373-.906c0-.356.124-.658.373-.907l.027-.027c.267-.249.573-.373.92-.373.347 0 .653.124.92.373L9.653 4.44c.071.071.134.142.187.213h4.267a.836.836 0 0 1 .16-.213l2.853-2.747c.267-.249.573-.373.92-.373.347 0 .662.151.929.4.267.249.391.551.391.907 0 .355-.124.657-.373.906L17.813 4.653zM5.333 7.24c-.746.018-1.373.276-1.88.773-.506.498-.769 1.13-.786 1.894v7.52c.017.764.28 1.395.786 1.893.507.498 1.134.756 1.88.773h13.334c.746-.017 1.373-.275 1.88-.773.506-.498.769-1.129.786-1.893v-7.52c-.017-.765-.28-1.396-.786-1.894-.507-.497-1.134-.755-1.88-.773H5.333zM8 11.107c.373 0 .684.124.933.373.25.249.383.569.4.96v1.173c-.017.391-.15.711-.4.96-.249.25-.56.374-.933.374s-.684-.125-.933-.374c-.25-.249-.383-.569-.4-.96V12.44c.017-.391.15-.711.4-.96.249-.249.56-.373.933-.373zm8 0c.373 0 .684.124.933.373.25.249.383.569.4.96v1.173c-.017.391-.15.711-.4.96-.249.25-.56.374-.933.374s-.684-.125-.933-.374c-.25-.249-.383-.569-.4-.96V12.44c.017-.391.15-.711.4-.96.249-.249.56-.373.933-.373z'
    })
  ])
}

// 自定义微博图标
const LogoWeibo = () => {
  return h('svg', {
    xmlns: 'http://www.w3.org/2000/svg',
    viewBox: '0 0 24 24',
    width: '1em',
    height: '1em'
  }, [
    h('path', {
      fill: 'currentColor',
      d: 'M10.098 20c-4.038 0-7.798-1.876-7.798-4.967 0-1.424.587-3.091 1.598-4.669.963-1.504 2.453-3.102 4.285-4.109 1.33-.728 2.462-1.057 3.414-.997.697.044 1.308.337 1.773.859.732.822.98 1.708 1.02 2.413.046.813-.059 1.414-.137 1.859l-.066.366.371-.055c.13-.019.273-.033.416-.033.11 0 .221.007.33.019 1.624.18 2.736 1.355 2.736 2.889 0 3.058-3.675 6.425-7.942 6.425zm-5.336-4.784c0 2.044 2.966 3.51 5.336 3.51 3.554 0 6.486-2.828 6.486-4.969 0-.934-.604-1.555-1.416-1.645a1.761 1.761 0 0 0-.524-.001l.016-.09c.077-.433.235-1.326.177-2.385-.03-.517-.198-1.059-.605-1.522-.16-.18-.43-.333-.813-.355-.667-.043-1.583.219-2.659.818-1.648.9-2.979 2.362-3.839 3.699-.876 1.36-1.33 2.647-1.33 3.662l.003.045c-.003.076.003.153.017.228.006.043.015.086.026.128a.507.507 0 0 0 .125.177z'
    }),
    h('path', {
      fill: 'currentColor',
      d: 'M9.15 18.619c-2.473 0-4.479-1.16-4.479-2.588 0-1.429 2.006-2.587 4.479-2.587s4.478 1.158 4.478 2.587c0 1.428-2.005 2.588-4.478 2.588zm-2.356-2.588c0 .696 1.059 1.245 2.356 1.245s2.355-.549 2.355-1.245c0-.695-1.058-1.244-2.355-1.244s-2.356.549-2.356 1.244z'
    }),
    h('path', {
      fill: 'currentColor',
      d: 'M14.604 11.741a.47.47 0 0 0 .471-.47c0-.26-.211-.47-.471-.47a.47.47 0 0 0 0 .94zM13.837 10.754a.705.705 0 1 0 0-1.41.705.705 0 0 0 0 1.41z'
    }),
    h('path', {
      fill: 'currentColor',
      d: 'M14.137 9.413c-2.13-.444-4.157 1.381-4.22 1.444a.387.387 0 0 0-.016.547.385.385 0 0 0 .547.016c.013-.013 1.749-1.545 3.455-1.193.21.044.415-.092.458-.303a.387.387 0 0 0-.224-.511z'
    }),
    h('path', {
      fill: 'currentColor',
      d: 'M19.646 7.016a.387.387 0 0 0-.546.024c-.45.512-1.678 1.905-3.127 2.205-1.647.341-3.186-.87-3.206-.889a.387.387 0 0 0-.547.042.387.387 0 0 0 .042.546c.087.08 1.806 1.431 3.758 1.035 1.703-.345 3.082-1.931 3.601-2.517a.387.387 0 0 0 .025-.546'
    })
  ])
}

const route = useRoute()
const router = useRouter()
const message = useMessage()

// 默认头像
const defaultAvatar = '/default-avatar.png'

// 用户信息
const userInfo = reactive({
  id: route.params.id as string || 'user123',
  username: 'shadow_master',
  nickname: '影子大师',
  avatar: 'https://picsum.photos/id/1005/200/200',
  bio: '专注于皮影动画创作，热爱传统文化与现代技术的结合。',
  level: 5,
  isCreator: true,
  isFollowed: false,
  workCount: 42,
  followingCount: 128,
  followerCount: 356,
  likeCount: 2451,
  createdAt: '2022-03-15T08:30:00Z',
  lastActiveAt: '2023-11-20T15:45:30Z',
  socialLinks: [
    { platform: 'bilibili', url: 'https://bilibili.com/123456', displayName: 'B站: 影子大师' },
    { platform: 'weibo', url: 'https://weibo.com/shadowmaster', displayName: '微博: @影子大师' }
  ]
})

// 判断是否为当前登录用户
const isCurrentUser = computed(() => {
  // 实际项目中应该与当前登录用户ID比较
  return userInfo.id === 'user123'
})

// 更多选项菜单
const moreOptions = [
  {
    label: '分享个人主页',
    key: 'share',
    icon: () => h(NIcon, null, { default: () => h(ShareSocialOutline) })
  },
  {
    label: '复制主页链接',
    key: 'copy-link',
    icon: () => h(NIcon, null, { default: () => h(CopyOutline) })
  },
  {
    label: '举报用户',
    key: 'report',
    icon: () => h(NIcon, null, { default: () => h(FlagOutline) })
  }
]

// 处理更多选项菜单选择
const handleMoreAction = (key: string) => {
  switch (key) {
    case 'share':
      // 分享个人主页
      message.info('分享功能开发中...')
      break
    case 'copy-link':
      // 复制个人主页链接
      const url = window.location.href
      navigator.clipboard.writeText(url).then(() => {
        message.success('链接已复制到剪贴板')
      }).catch(() => {
        message.error('复制失败，请手动复制')
      })
      break
    case 'report':
      // 举报用户
      message.info('举报功能开发中...')
      break
  }
}

// 作品筛选和排序
const worksFilter = ref('all')
const sortBy = ref('latest')
const sortOptions = [
  { label: '最新发布', value: 'latest' },
  { label: '最多播放', value: 'most-viewed' },
  { label: '最多点赞', value: 'most-liked' }
]

// 分页相关
const currentPage = ref(1)
const collectionsCurrentPage = ref(1)
const pageSize = 12
const totalWorks = ref(42)
const totalCollections = ref(18)
const totalPages = computed(() => Math.ceil(totalWorks.value / pageSize))
const collectionsPages = computed(() => Math.ceil(totalCollections.value / pageSize))

// 用户作品列表
const userWorks = ref([
  {
    id: 'work1',
    title: '皮影戏《西游记》片段',
    thumbnail: 'https://picsum.photos/id/237/300/200',
    duration: 180000, // 毫秒
    views: 12500,
    likes: 1024,
    createdAt: '2023-10-15T10:30:00Z'
  },
  {
    id: 'work2',
    title: '《牛郎织女》现代演绎',
    thumbnail: 'https://picsum.photos/id/238/300/200',
    duration: 240000,
    views: 8700,
    likes: 756,
    createdAt: '2023-09-20T14:20:00Z'
  },
  {
    id: 'work3',
    title: '动画短片《影子的旅行》',
    thumbnail: 'https://picsum.photos/id/239/300/200',
    duration: 320000,
    views: 15200,
    likes: 1358,
    createdAt: '2023-08-05T09:15:00Z'
  },
  {
    id: 'work4',
    title: '传统皮影技法教学',
    thumbnail: 'https://picsum.photos/id/240/300/200',
    duration: 900000,
    views: 5600,
    likes: 432,
    createdAt: '2023-07-12T16:40:00Z'
  }
])

// 用户收藏列表
const userCollections = ref([
  {
    id: 'collection1',
    title: '《水浒传》皮影动画',
    thumbnail: 'https://picsum.photos/id/241/300/200',
    duration: 420000,
    author: '皮影艺术家',
    views: 23400,
    likes: 2100
  },
  {
    id: 'collection2',
    title: '现代风格皮影秀',
    thumbnail: 'https://picsum.photos/id/242/300/200',
    duration: 180000,
    author: '新锐动画师',
    views: 9800,
    likes: 876
  }
])

// 格式化数字（超过1000显示为1k）
function formatNumber(num: number): string {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化时长
function formatDuration(ms: number): string {
  return DateUtils.formatDuration(ms, 'mm:ss')
}

// 格式化日期
function formatDate(dateString: string | Date, format: string = 'MM-DD'): string {
  return DateUtils.format(dateString, format)
}

// 获取社交平台图标
function getSocialIcon(platform: string) {
  const iconMap: Record<string, any> = {
    github: LogoGithub,
    twitter: LogoTwitter,
    youtube: LogoYoutube,
    instagram: LogoInstagram,
    bilibili: LogoBilibili,
    weibo: LogoWeibo,
    // 其他平台图标...
    default: LogoGithub
  }
  
  return iconMap[platform.toLowerCase()] || iconMap.default
}

// 编辑个人资料
function editProfile() {
  router.push('/user/profile/edit')
}

// 关注/取消关注
function toggleFollow() {
  userInfo.isFollowed = !userInfo.isFollowed
  if (userInfo.isFollowed) {
    userInfo.followerCount++
    message.success('关注成功')
  } else {
    userInfo.followerCount--
    message.success('已取消关注')
  }
}

// 发送消息
function sendMessage() {
  message.info('消息功能开发中...')
  // 实际项目中应该跳转到消息页面或打开消息对话框
}

// 查看作品详情
function viewWorkDetail(workId: string) {
  router.push(`/work-detail/${workId}`)
}

// 加载用户数据
function loadUserData() {
  // 实际项目中应该从API获取用户数据
  console.log('Loading user data for ID:', route.params.id)
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserData()
})
</script>

<style lang="scss" scoped>
.user-profile-container {
  padding: 20px;
  
  .profile-card {
    margin-bottom: 20px;
    
    .profile-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      
      .profile-info {
        display: flex;
        gap: 20px;
        
        .avatar-container {
          position: relative;
          
          .creator-badge {
            position: absolute;
            bottom: 0;
            right: 0;
            color: #18a058;
            font-size: 22px;
          }
        }
        
        .user-info {
          display: flex;
          flex-direction: column;
          justify-content: center;
          
          .username {
            font-size: 24px;
            font-weight: 500;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            
            .level-tag {
              margin-left: 8px;
            }
          }
          
          .user-id {
            color: var(--text-color-3);
            font-size: 14px;
            margin-bottom: 8px;
          }
          
          .bio {
            margin-bottom: 16px;
            max-width: 500px;
            color: var(--text-color-2);
          }
          
          .stats {
            display: flex;
            gap: 24px;
            
            .stat-item {
              text-align: center;
              
              .stat-value {
                font-size: 18px;
                font-weight: 500;
              }
              
              .stat-label {
                font-size: 12px;
                color: var(--text-color-3);
              }
            }
          }
        }
      }
    }
  }
  
  .content-tabs {
    .tab-content {
      padding: 16px 0;
      
      .filter-bar {
        margin-bottom: 16px;
      }
      
      .works-grid,
      .collections-grid {
        .work-card {
          cursor: pointer;
          transition: transform 0.2s;
          
          &:hover {
            transform: translateY(-4px);
          }
          
          .work-thumbnail {
            position: relative;
            height: 150px;
            overflow: hidden;
            border-radius: 3px;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .work-duration {
              position: absolute;
              bottom: 8px;
              right: 8px;
              background-color: rgba(0, 0, 0, 0.6);
              color: white;
              padding: 2px 6px;
              border-radius: 2px;
              font-size: 12px;
            }
          }
          
          .work-info {
            padding: 8px 0;
            
            .work-title {
              font-weight: 500;
              margin-bottom: 4px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .work-meta {
              display: flex;
              font-size: 12px;
              color: var(--text-color-3);
              
              .meta-item {
                display: flex;
                align-items: center;
                margin-right: 12px;
                
                .n-icon {
                  margin-right: 4px;
                  font-size: 14px;
                }
              }
            }
          }
        }
        
        .pagination {
          margin-top: 24px;
          display: flex;
          justify-content: center;
        }
      }
      
      .about-card {
        margin-bottom: 16px;
        
        .social-link {
          margin-bottom: 8px;
        }
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-profile-container {
    padding: 12px;
    
    .profile-card {
      .profile-header {
        flex-direction: column;
        
        .profile-info {
          margin-bottom: 16px;
        }
        
        .profile-actions {
          width: 100%;
          display: flex;
          justify-content: center;
        }
      }
    }
    
    .content-tabs {
      .works-grid,
      .collections-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}
</style> 